package com.hhxy.service;

import com.hhxy.mapper.BrandMapper;
import com.hhxy.pojo.Brand;
import com.hhxy.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    SqlSessionFactory sqlSF = SqlSessionFactoryUtil.getSqlSF();

    /**
     * 查询表中所有数据的方法
     * @return
     */
    public List<Brand> selectAll(){
        //1、调用工具类获取SqlSessionFactory对象
        //2、获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //3、获取Mapper接口对象
        BrandMapper mapper = sqlS.getMapper(BrandMapper.class);
        //4、执行SQL语句
        List<Brand> brands = mapper.selectAll();
        //5、释放资源
        sqlS.close();
        return brands;
    }

    public boolean add(Brand brand){
        //1、调用工具类获取SqlSessionFactory对象
        //2、获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //3、获取Mapper接口对象
        BrandMapper mapper = sqlS.getMapper(BrandMapper.class);
        //4、执行SQL语句
        //排除非空数据，brand==null 结果为false，这里有待优化
        if(brand.getBrandName() == null || brand.getOrdered() == null || brand.getOrdered() == null ||
                brand.getDescription() == null || brand.getStatus() == null){
            return false;
        }
        mapper.add(brand);
        //添加数据需要提交事物，未设置自动提交事物，就需要手动提交事物！
        sqlS.commit();
        //5、释放资源
        sqlS.close();
        return true;
    }
}